package util

import (
	"fmt"
	"github.com/chromedp/cdproto/network"
	"io/ioutil"
	"log"
	"mp3/entity"
	"net/http"
	"strings"
)

func Download(url string, configEntity entity.DownloadEntity, title string, heads map[string]string, cookies []*network.Cookie) (bool, string) {
	path := configEntity.FileDirPath + "/" + title + configEntity.AudioType
	log.Println(path, url, "-Http--start")
	v, flag := createResponse(url, heads, cookies)
	if !flag {
		return false, path
	}
	defer func() {
		if nil != v && nil != v.Body {
			v.Body.Close()
			v.Body = nil
		}
		v = nil
	}()
	//SleepTime(500)
	content, err := ioutil.ReadAll(v.Body)
	if err != nil {
		fmt.Printf("Read http response failed! %v", err)
		return false, path
	}

	err = ioutil.WriteFile(path, content, 0666)
	if err != nil {
		fmt.Printf("Save to file failed! %v", err, err)
		return false, path
	} else {
		if !ValudateFile(configEntity, path) {
			return false, path
		}
		//	SleepTime(Default_Sleep_Value)
		log.Println(path, url, "-Http--Over")
	}

	return true, path
}

func createResponse(url string, heads map[string]string, cookies []*network.Cookie) (*http.Response, bool) {
	client := &http.Client{Timeout: Default_Sleep_Value_HTTP}
	req, err := http.NewRequest("GET", strings.TrimSpace(url), nil)

	if nil != err {
		log.Println(url, "---request---", err)
		return nil, false
	}

	if len(heads) > 0 {
		for key := range heads {
			req.Header.Add(key, heads[key])
		}
	}

	if len(cookies) > 0 {
		builder := strings.Builder{}
		for _, cookie := range cookies {
			if cookie.Name == "ASPSESSIONIDCAQBQBDT" {
				continue
			}
			builder.WriteString(cookie.Name + "=" + cookie.Value + ";")
		}
		req.Header.Add("Cookie", builder.String())
	}

	resp, error := client.Do(req)
	if nil != error {
		log.Println(url, "---client.Do---", err)
		return nil, false
	}
	log.Println(url, "---client.Do---", resp.Status)
	//time.Sleep(Sleep_Value)
	return resp, true

}
